#!/usr/bin/python3
# -*- coding: utf-8 -*-

__author__ = "muttley"
__copyright__ = "Copyright 2013"
__credits__ = ["muttley"]
__license__ = "GPL"
__prg_name__ = "stn"
__version__ = "1.1b"
__maintainer__ = "muttley"
__email__ = "rob@spot.colorado.edu"
__status__ = "Production"


# TODO:
# 1. Separare baseStn da scraper...come trigger e notify
# 2. Generalizzare scraper e trigger che si somigliano
# 3. sia scraper che trigger possono chiamare scraper, trigger e notify (generalizzare)

# System lib
import os
import sys
from optparse import OptionParser

# Local lib
from lib.base.core import baseStn
from lib.utils.utils import *
from lib.utils.jsoncfg import jsonCfg
from lib.utils.justmatched import justMatched
from lib.utils.coloredformatter import *

""" DEFAULT VARIABLE """
# Script file name
__script = os.path.basename(sys.argv[0])
# Script file absolute path
__script_path = os.path.abspath(os.path.dirname(sys.argv[0]))

# Path
__config_file = '/etc/stn.json'
__log_file = None

# Log format (attributes: http://docs.python.org/2/library/logging.html#logrecord-attributes)
__log_formatter = '(%(asctime)s) [%(levelname)-19s][$BOLD%(name)s$RESET] %(message)s ($BOLD%(filename)s$RESET:%(lineno)d)'
__log_formatter_file = '(%(asctime)s) [%(levelname)-8s][$BOLD%(name)s$RESET] %(message)s ($BOLD%(filename)s$RESET:%(lineno)d)'
__log_formatter_date = "%Y-%m-%d %H:%M:%S"

# Init SQLlite
jm = justMatched()
jm.createTable()


def main ():
    """ CLI OPTION """
    
    # Help message
    usage = "usage: %prog [-fv] [-c CONFIGFILE] [-l LOGFILE] [-p PIDFILE -s]\n"\
            "   es: %prog -c /path/to/my.cfg\n"\
            "       %prog -fvvv"
            
    description = "%prog (ScrapTrigNotify) scrap web pages, trig on any selected case and notify (mail, push, log, etc)."
    version = " %prog " +  __version__  # --version to print
    
    # Program parsed option
    
    parser = OptionParser(usage=usage, description=description, epilog=__copyright__, version=version)
    
    parser.add_option("-c", "--cfg", type="string", dest="cfgFile", default=__config_file,
                      help=("alternative config file (default: %s)" % __config_file))
    
    parser.add_option("-l", "--log", type="string", dest="logFile", default=__log_file,
                      help="log to file (for default log on standard output)")
                    
    parser.add_option("-f", "--foreground", action="store_true", dest="foreground", default=False,
                      help="No daemon mode. Start %prog in foreground")
    
    parser.add_option("-v", "--verbose", action="count", dest="verbosity", default=2,
                      help="Enable (and increase) verbosity. Repeatable option. (max 4)")
    
    parser.add_option("-p", "--pidfile", type="string", dest="pidFile", default=None,
                      help="Manage pidfile when start in daemon mode")
    
    parser.add_option("-s", "--stop", action="store_true", dest="stop", default=False,
                      help="Stop deamon mode. Use always with -p")
    
    
    (options, args) = parser.parse_args()
    
    # Manage param and error  
    
    
    """ LOGGING """
    
    logger = logging.getLogger(__prg_name__)
    
    # verbosity of root to send to handler (set higher, after "filter" in handler)
    logger.setLevel(logging.DEBUG_02)
    
    # log on file or on stdout
    if(options.logFile is not None):
        # create file handler (log on file)
        logHandler = logging.FileHandler(options.logFile, 'a')
        
        # create formatter without color (attributes: http://docs.python.org/2/library/logging.html#logrecord-attributes)
        formatter = coloredFormatter(__log_formatter_file, False, __log_formatter_date)
    else:
        # crete stdout handler
        logHandler = logging.StreamHandler()
        
        # create formatter with color (attributes: http://docs.python.org/2/library/logging.html#logrecord-attributes)
        formatter = coloredFormatter(__log_formatter, True, __log_formatter_date)
    
    # Add loggin level to python default (definited in lib.utils.utils)
    logging.addLevelName(logging.DEBUG_01 , 'DEBUG.01')
    logging.addLevelName(logging.DEBUG_02 , 'DEBUG.02')
    
    # Match, number of verbosity (count of 'v') with log levels
    verbosity2logLvl = [logging.CRITICAL, logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG, logging.DEBUG_01 , logging.DEBUG_02]
    # Set color for logging level
    formatter.setColors( {'CRITICAL': YELLOW,'ERROR': RED,'WARNING': YELLOW,'INFO': WHITE,'DEBUG': BLUE,'DEBUG.01': GREEN,'DEBUG.02': MAGENTA})
    
    # set log verbosity
    logHandler.setLevel(verbosity2logLvl[options.verbosity])
    # set log format
    logHandler.setFormatter(formatter)
    
    # add the handlers to logger
    logger.addHandler(logHandler)

    """ DEMONIZE """
    # run background or in foreground
    daemon = stnDaemon(options.cfgFile, __prg_name__, options.pidFile)
    if(options.foreground is True):
        logger.info('Start in foreground (No daemon mode)')
        daemon.run()
    else:
        if(options.stop is True):
            logger.info('Stop daemon')
            daemon.stop()
        else:
            logger.info('Start daemon')
            daemon.start()
    
    # exit without errors
    sys.exit(0)
 
   
from lib.utils.daemon import daemon
 
class stnDaemon(daemon):
    cfgFile = logger = loggerName = None
    
    # create a sub logger of root
    def __init__(self, cfgFile, loggerName, pidFile):
        self.cfgFile = os.path.abspath(cfgFile)
        self.loggerName = loggerName
        self.logger = logging.getLogger(self.loggerName + '.daemon')

        super().__init__(pidFile)
    
    # real body process
    def run(self):
        dictCfg = jsonCfg()
        
        if(os.path.exists(self.cfgFile) is False):
           self.logger.error('The config file (%s) NOT exist!' % self.cfgFile)
        
        dictCfg.open(self.cfgFile)
        self.logger.info('Open config file: %s' % self.cfgFile)
        
        # make this beacause I change dict structure during cicle
        lstKey = list(dictCfg.keys())
        
        # cicle on profile
        for key in lstKey:
            # ignore profile name that start with '__'
            if(key[0:2] != '__'):
                stn = baseStn(dictCfg, key, self.loggerName)
                stn.run()
       

if __name__ == "__main__":
    main()
